import React from 'react';
import moment from 'moment';
import cn from 'classnames';
import styles from './index.module.less';
import { initialize, destroy, setOption, resize } from './touch';
import { isDoubleClick } from './utils';

const hours = [...Array(24).keys()];

const CELL_HEIGHT = 32; // 行高
const MIN_MINUTE = 15; // 最小分钟限制

const getNumberOfDate = dateStr => moment(dateStr).hour() + moment(dateStr).minute() / 60;
const getFillItemStyle = (range, extra = {}) => {
    if (!range) return {};
    const [start, end] = range;
    const startValue = getNumberOfDate(start);
    const endValue = getNumberOfDate(end);
    return {
        width: '100%',
        top: startValue * CELL_HEIGHT,
        height: (endValue - startValue) * CELL_HEIGHT,
        zIndex: 2,
        ...extra
    };
};
const formatRule = 'YYYY-MM-DD HH:mm';
const defaultRangeList = [
    {
        id: 1,
        range: [
            moment()
                .hour(2)
                .minute(0)
                .format(formatRule),
            moment()
                .hour(3)
                .minute(0)
                .format(formatRule)
        ]
    },
    {
        id: 2,
        range: [
            moment()
                .hour(13)
                .minute(0)
                .format(formatRule),
            moment()
                .hour(14)
                .minute(30)
                .format(formatRule)
        ]
    }
];

// 最小刻度
const fixBound = date => date.minute(Math.round(date.minute() / MIN_MINUTE) * MIN_MINUTE);

const nextRangeHandlerMap = {
    move: (range, hour) => [
        fixBound(moment(range[0]).add(hour, 'h')).format(formatRule),
        fixBound(moment(range[1]))
            .add(hour, 'h')
            .format(formatRule)
    ],
    expandUp: (range, hour) => [fixBound(moment(range[0]).add(hour, 'h')).format(formatRule), range[1]],
    expandDown: (range, hour) => [range[0], fixBound(moment(range[1]).add(hour, 'h')).format(formatRule)]
};

const Schedule = ({ height }) => {
    const [rangeList, setRangeList] = React.useState(defaultRangeList);

    const handleChange = (index, distance, type) => {
        const adjustHour = parseFloat((distance / CELL_HEIGHT).toFixed(1));
        setRangeList(
            rangeList.map((item, itemIndex) => {
                if (index === itemIndex) {
                    console.log(nextRangeHandlerMap[type](item.range, adjustHour), 'date');
                    return {
                        ...item,
                        range: nextRangeHandlerMap[type](item.range, adjustHour)
                    };
                }
                return item;
            })
        );
    };

    const handleAddRange = hour => {
        const nextId = rangeList.length ? Math.max(...rangeList.map(item => item.id)) : 0;
        setRangeList([
            ...rangeList,
            {
                id: nextId + 1,
                range: [
                    moment()
                        .hour(hour)
                        .minute(0)
                        .format(formatRule),
                    moment()
                        .hour(hour + 1)
                        .minute(0)
                        .format(formatRule)
                ]
            }
        ]);
    };

    const handleRemoveRange = id => {
        if (!isDoubleClick()) return;
        setRangeList(rangeList.filter(item => item.id !== id));
    };

    React.useEffect(() => {
        initialize();
        return () => {
            destroy();
        };
    }, []);

    // rangeList需要更新
    React.useEffect(() => {
        setOption({
            onComplete: handleChange,
            minMinute: MIN_MINUTE // 最小单位时间 分钟
        });
    }, [rangeList]);

    React.useEffect(() => {
        resize();
    }, [height]);

    return (
        <div className={styles.wrap}>
            <div className={cn(styles.context, 'touch-scroll')} style={{ height }}>
                <div className={styles.hours}>
                    <div className={styles.hourItem}></div>
                    <div className={styles.hourDegree}>
                        {hours.map(hour => (
                            <div className={styles.hourItem} key={hour}>
                                {`0${hour}:00`.substr(-5)}
                            </div>
                        ))}
                    </div>
                </div>
                <div className={styles.detail}>
                    <div className={cn(styles.detailColumn, 'touch-context')}>
                        {hours.map(hour => (
                            <div
                                key={hour}
                                className={styles.cell}
                                onClick={() => {
                                    handleAddRange(hour);
                                }}
                            />
                        ))}
                        {rangeList.map(item => (
                            <div
                                key={item.id}
                                className={cn(styles.fillItem, 'touch-item')}
                                style={getFillItemStyle(item.range)}
                                onClick={e => {
                                    e.preventDefault();
                                    handleRemoveRange(item.id);
                                }}
                            >
                                <div className={cn(styles.topDot, 'touch-expand-up')}></div>
                                <div className={cn(styles.bottomDot, 'touch-expand-down')}></div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Schedule;
